package com.zhiyume.service;

import com.zhiyume.dao.api.TOauthMapper;
import com.zhiyume.dao.api.TUserMapper;
import com.zhiyume.dao.entity.TOauth;
import com.zhiyume.dao.entity.TOauthCriteria;
import com.zhiyume.dao.entity.TUser;
import com.zhiyume.dao.entity.TUserCriteria;
import com.zhiyume.dto.LoginResDTO;
import com.zhiyume.service.common.ConstantEnum;
import com.zhiyume.service.common.UserEnum;
import com.zhiyume.service.util.DateUtil;
import com.zhiyume.service.util.GenerateKeyUtil;
import com.zhiyume.util.RedisClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author jiaxz
 * @date 2017/11/22 20:55
 * @description
 */
@Service
@Transactional
public class OauthLoginService {
    @Autowired
    private TOauthMapper tOauthMapper;
    @Autowired
    private TUserMapper tUserMapper;
    @Autowired
    private RedisClient redisClient;


    private static final String MODULE = OauthLoginService.class.getCanonicalName();
    private static final Logger logger = LoggerFactory.getLogger(OauthLoginService.class);


    public LoginResDTO oauthLogin(String openId, String oauthType,String nickName,String headImgUrl) {
        logger.info("【微信】"+oauthType+"【微信】"+openId+"【微信】"+nickName+"【微信】"+headImgUrl);
        TOauthCriteria example = new TOauthCriteria();
        TOauthCriteria.Criteria c = example.createCriteria();
        c.andOpenidEqualTo(openId);
        c.andStatusEqualTo(UserEnum.USER_STATUS_NORMAL.getValue());
        List<TOauth> oauths = tOauthMapper.selectByExample(example);
        LoginResDTO loginResDTO = new LoginResDTO();
        //openid已存在
        if (null != oauths && oauths.size() > 0) {
            TOauth oauth = oauths.get(0);
            long id = oauth.getId();
            TUserCriteria userCriteria = new TUserCriteria();
            TUserCriteria.Criteria criteria = userCriteria.createCriteria();
            criteria.andIdEqualTo(id);
            List<TUser> users = tUserMapper.selectByExample(userCriteria);
            if(null!=users || users.size() > 0){
                TUser user = users.get(0);
                user.setNickName(nickName);
                user.setFaceUrl(headImgUrl);
                user.setUpdateTime(DateUtil.getNow());
                tUserMapper.updateByPrimaryKeySelective(user);
            }else {
                return loginResDTO;
            }
            String token = UUID.randomUUID().toString().toLowerCase() + new Date().getTime();
            try {
                redisClient.setx(ConstantEnum.CONSTANT_TOKEN_PRE.getErrType() + token, String.valueOf(id), UserEnum.USER_TOKEN_TIME.getValue());
            } catch (Exception e) {
                logger.error(e.getMessage());
                return loginResDTO;
            }
            loginResDTO.setToken(token);
            loginResDTO.setuId(id);
        } else {
            //openid不存在，先注册后登陆
            String nowDate = DateUtil.getNow();
            long id = GenerateKeyUtil.generationPK();
            TOauth tOauth = new TOauth();
            tOauth.setCreateTime(nowDate);
            tOauth.setId(id);
            tOauth.setOpenid(openId);
            tOauth.setStatus(UserEnum.USER_STATUS_NORMAL.getValue());
            tOauth.setOauthType(Integer.parseInt(oauthType));
            tOauthMapper.insertSelective(tOauth);
            TUser tUser = new TUser();
            tUser.setId(id);
            tUser.setCreateTime(nowDate);
            tUser.setStatus(UserEnum.USER_STATUS_NORMAL.getValue());
            tUser.setFaceUrl(headImgUrl);
            tUser.setNickName(nickName);
            tUserMapper.insertSelective(tUser);
            String token = UUID.randomUUID().toString().toLowerCase() + new Date().getTime();
            try {
                redisClient.setx(ConstantEnum.CONSTANT_TOKEN_PRE.getErrType() + token, String.valueOf(id), UserEnum.USER_TOKEN_TIME.getValue());
            } catch (Exception e) {
                logger.error(e.getMessage());
                return loginResDTO;
            }
            loginResDTO.setToken(token);
            loginResDTO.setuId(id);
        }
        return loginResDTO;
    }
}
